package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
@WebFilter("/*")
public class LoginFilter implements Filter {
    public static final AntPathMatcher MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //向下转型
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //过滤器需要当前访问路径
        String requestURI = request.getRequestURI();
        //定义放行路径存在多个，数组
        String [] urls = new String[]{"/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**" ,
                "/user/sendMsg",
                "/user/login"};
        //得到当前路径是否是放行路径的返回结果
        boolean check = check(urls, requestURI);
        //开始判断,先判断当前路径请求是否需要处理
        if (check){
            //进来的不需要处理，直接放行
            filterChain.doFilter(request,response);
            BaseContext.removeCurrentId();
            return;
        }
        //当前路径是否登录，根据之前的Session数据判断
        if (request.getSession().getAttribute("employee")!=null){
            //能够获取到数据放行
            Long empId = (Long) request.getSession().getAttribute("employee");
            BaseContext.setCurrentId(empId);
            filterChain.doFilter(request,response);
            BaseContext.removeCurrentId();
            return;
        }
        //当前路径是否登录，根据之前的Session数据判断
        if (request.getSession().getAttribute("user")!=null){
            //能够获取到数据放行
            Long userId = (Long) request.getSession().getAttribute("user");
            BaseContext.setCurrentId(userId);
            filterChain.doFilter(request,response);
            BaseContext.removeCurrentId();
            return;
        }
        //根据前段数据，前端有相应的跳转界面，返回对应的数据
        //通过输出流写出JSON数据
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;

    }
    //定义一个方法，判断当前路径是否是数组中的路径
    public static boolean check(String [] urls,String requsetURI){
        for (String url : urls) {
            if (MATCHER.match(url,requsetURI)){
                return true;
            }
        }
        return false;
    }
}
